//
//  OrderListViewController.swift
//  WineComing
//
//  Created by xiaozhi on 15/7/20.
//  Copyright (c) 2015年 xiaozhi. All rights reserved.
//

import UIKit
enum OrderStatus{
    case NS_Status_Pending,NS_Status_Paid,NS_Status_compelete
}
class OrderListViewController: BaseViewController {
    var tableview:UITableView!
    var dataArray:[orderListItemObj]! = []
    var currentOrderId:String = ""
    var currentOrder:orderListItemObj?
    var currentNumber:NSInteger = 0
    var totalNumber:NSInteger = 0
    var currentPage:NSInteger = 1
    let length:NSInteger = 12
    var requestOrderType:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.title = "订单列表"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        self.createTableView()
       
       
        // Do any additional setup after loading the view.
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
        self.tableview.header.beginRefreshing()

    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func createTableView(){
        //        leftTableDataSource.addObjectsFromArray(["热门品牌","食品/保健","美妆个护","母婴用品","服饰鞋包","生活数码"])
        tableview = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, view.bounds.size.height-64), style: UITableViewStyle.Grouped)
        tableview.backgroundColor = UIColor.clearColor();
        tableview.separatorStyle = UITableViewCellSeparatorStyle.None
        tableview.showsHorizontalScrollIndicator = false
        tableview.showsVerticalScrollIndicator = false
        tableview.dataSource = self
        tableview.delegate = self
        let nib = UINib(nibName:"OrderlistCell", bundle:nil)
        tableview.registerNib(nib,forCellReuseIdentifier:"OrderlistCell")
        tableview.header =  MJRefreshNormalHeader(refreshingBlock:{[weak self] in
                self?.currentNumber = 0
                self?.currentPage = 1
                self?.queryOrderList(GlobalDataHelper.instance.session, orderstatus:self!.requestOrderType, offset: self!.currentPage, length: self!.length)
            }
        )
        tableview.footer =  MJRefreshAutoNormalFooter(refreshingBlock:{[weak self] in
                self?.currentPage++
                self?.queryOrderList(GlobalDataHelper.instance.session, orderstatus:self!.requestOrderType, offset: self!.currentPage, length: self!.length)
            }
        )
        tableview.footer.hidden = true
        view.addSubview(tableview)
    }
    func queryOrderList(sessionid:String!,orderstatus:String!,offset:Int,length:Int)->Void{
        if GlobalDataHelper.instance.session == nil{
            return
        }
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(sessionid, forKey: "sessionid")
        parameters.setObject(orderstatus, forKey: "orderstatus")
        parameters.setObject(NSNumber(integer: offset),forKey: "c")
        parameters.setObject(NSNumber(integer:length), forKey: "s")
        request.requestStart("/account_order/list", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                }
                if (dic?["result"])! as! String == "0"{
                    if let array = dic?.pareseDataToOrderListArray(){
                        let total:NSString = dic?["data"]?["order_totals"] as! NSString
                        self.totalNumber = total.integerValue
                        if self.currentNumber == 0{
                            self.dataArray.removeAll(keepCapacity: false)
                            self.dataArray = array
                        }
                        else{
                            for i in 0..<array.count{
                                let obj:orderListItemObj = array[i]
                                self.dataArray.append(obj)
                            }
                        }
                        self.currentNumber = self.dataArray.count
                    }
                    dispatch_async(dispatch_get_main_queue()){
                        //添加成功处理
                        self.tableview.reloadData()
                        self.tableview.header.endRefreshing()
                        if self.currentNumber == self.totalNumber{
                            self.tableview.footer.noticeNoMoreData()
                        }
                        else{
                            self.tableview.footer.resetNoMoreData()
                        }
                        if self.tableview.contentSize.height<self.tableview.bounds.size.height{
                            self.tableview.footer.hidden = true
                        }
                        else{
                            self.tableview.footer.hidden = false
                        }
                    }
                }
            }
            else{
                dispatch_async(dispatch_get_main_queue()){
                    self.showTips("加载失败")
                    self.tableview.header.endRefreshing()
                    if self.currentNumber == self.totalNumber{
                        self.tableview.footer.noticeNoMoreData()
                    }
                    else{
                        self.tableview.footer.resetNoMoreData()
                    }
                    if self.tableview.contentSize.height<self.tableview.bounds.size.height{
                        self.tableview.footer.hidden = true
                    }
                    else{
                        self.tableview.footer.hidden = false
                    }
                }

            }
        })
        self.showProcess("加载中...")
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
    deinit{
        print("orderlist deinit")
    }
}

extension OrderListViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return dataArray.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return dataArray[section].items!.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("OrderlistCell", forIndexPath: indexPath) as! OrderlistCell
        if let objItem = dataArray[indexPath.section].items?[indexPath.row]{
            cell.wineImageView.setImageWithUrl(objItem.image!, defaultImage:nil)
            cell.wineTitle.text = objItem.name
            cell.wineNumber.text = "X "+objItem.qty!
            cell.totalMoney.text = objItem.price
            cell.otherInfo.text = "参数："+objItem.weight!
        }
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 80
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 30
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        let obj = dataArray[section]
//        if let status = obj.status{
//            switch status{
//                /************************************************
//                * 订单状态 : 1-下单
//                *           2-抢单
//                *           3-配送
//                *           4-收货
//                *           5-验货
//                *           6-评论
//                *           7-取消
//                *           8-删除
//                *           9-关闭
//                ************************************************/
//            case "1":return 40
//            case "2":return 40
//            case "3":return 40
//            case "4":return 40
//            case "5":return 40
//            case "6":return 1
//            case "7":return 1
//            case "8":return 1
//            case "9":return 1
//            case "10":return 1
//            default:return 1
//            }
//        }
//        return 1
//        if section%2 == 0{
//            return 40
//        }
//        else{
//            return 80
//        }
         return 80
    }
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?{
        let headView = NSBundle.mainBundle().loadNibNamed("OrderListHeadView", owner: nil, options: nil)[0] as! OrderListHeadView
        let obj = dataArray[section]
        headView.orderNumber.text = "订单号："+obj.increment_id!
        headView.orderDate.text = obj.created_time
        if let status = obj.status{
            switch status{
                //orderStatus pending未支付  paid已支付  complete已完成
            case "pending":
                headView.orderState.text = "未支付"
            case "paid":headView.orderState.text = "已支付"
            case "complete":headView.orderState.text = "已完成"
//            case "4":headView.orderState.text = "已收货"
//            case "5":headView.orderState.text = "已验货"
//            case "6":headView.orderState.text = "已完成"
//            case "7":headView.orderState.text = "已取消"
//            case "8":headView.orderState.text = "已删除"
//            case "9":headView.orderState.text = "已完成"
//            case "10":headView.orderState.text = "已超时"
            default:break
            }
        }
        return headView
        
    }
    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView?{
        var height:CGFloat = 80.0
//        if section%2 != 0{
//            height =  80.0
//        }
        let footView = OrderListFootView(frame: CGRectMake(0, 0, tableView.bounds.size.width, height))
        footView.section = section
        let obj = dataArray[section]
       
        if let number = obj.items?.count{
            
            let info = NSString(format:"共%d件商品,合计 ¥%@(含运费%@块)",number, obj.total!,obj.shipping_amount!)
            let search = NSString(format:"¥%@",obj.total!)
            footView.setInfo(info as String, highLightInfo: search as String)
        }
//        if section%2 == 0{
//            footView.setupView(true, buttonWithTitle:"")
//        }
//        else{
//            footView.setupView(true, buttonWithTitle: "删除","评价","查看物流")
//        }
        if let status = obj.status{
            switch status{
                //orderStatus pending未支付  paid已支付  complete已完成
            case "pending":
               footView.setupView(true, buttonWithTitle:"继续支付")
            case "paid":footView.setupView(true, buttonWithTitle: "删除","评价","查看物流")
            case "complete":footView.setupView(true, buttonWithTitle: "删除","评价","查看物流")
            default:break
            }
        }
//        if let status = obj.status{
//            /************************************************
//            * 订单状态 : 1-下单
//            *           2-抢单
//            *           3-配送
//            *           4-收货
//            *           5-验货
//            *           6-评论
//            *           7-取消
//            *           8-删除
//            *           9-关闭
//            ************************************************/
//            switch status{
//            case "1":
//                if obj.status == "1"{
//                    footView.setupView(true, buttonWithTitle: "取消订单","继续支付")
//                }
//                else{
//                    footView.setupView(true, buttonWithTitle: "取消订单","查看状态")
//                }
//            case "2":
//                    footView.setupView(true, buttonWithTitle: "取消订单","查看状态")
//            case "3":
//                    footView.setupView(true, buttonWithTitle:"查看状态")
//            case "4":
//                    footView.setupView(true, buttonWithTitle:"查看状态","追加评价")
//            case "5":
//                    footView.setupView(false, buttonWithTitle:"查看状态","追加评价")
//            case "6":
//                    return nil
//            case "7":
//                    return nil
//            case "8":
//                return nil
//            default:return nil
//            }
//        }
        footView.btnEventHandle = {[weak footView,weak self] title,section in
//            self?.currentOrderId = obj.id!
            self?.currentOrder = obj
            if let name = title{
                switch name{
                    case "继续支付":
                        let ctl = PayViewController()
                        ctl.orderId = obj.increment_id
                        ctl.total = obj.total
                        ctl.continuePay = true
                        self?.navigationController?.pushViewController(ctl, animated: true)
                    case "取消订单":
                        let av = UIAlertView(title: "确定要取消该订单吗？", message: nil, delegate:self, cancelButtonTitle: "取消")
                        av.addButtonWithTitle("确定")
                        av.show()
//                    case "查看状态":
//                    self?.performSegueWithIdentifier("showOrderStatuFromOrderlist", sender: self)
//                    case "删除订单":
//                        var arequested = SoapRequestHelper()
//                        arequested.requestStart("deleteOrder", parameters: [("orderId",obj.id!),("md5","1111")],compeleteHandle: {(data, response, error) -> Void in
//                            if error==nil{
//                                self?.hiddenProcessView()
//                                let xmlHelper = XMLParseHelper(data: data,matchElement:"deleteOrderReturn",compeleteHandle:{responObj in
//                                    if let dic = responObj as? NSDictionary{
//                                        if (dic["result"] as! String) == "0"{
//                                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                                                self?.showTips("操作成功")
//                                                self?.dataArray.removeAtIndex(section)
//                                                self?.tableview.reloadData()
//                                                })
//                                        }
//                                        else{
//                                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                                                self?.showTips("取消失败")
//                                                })
//                                        }
//                                    }
//                                })
//                            }
//                            else{
//                                dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                                    self?.showTips("网络异常操作失败")
//                                    })
//                            }
//
//                            
//                        })
//                        self?.showProcess("正在处理")
//                    case "追加评价":
//                    self?.performSegueWithIdentifier("showCommentFromOrderlist", sender: self)
                default:break
                }
            }
            
        }
        return footView
    }
}
extension OrderListViewController:UIAlertViewDelegate{
//    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int){
//        if buttonIndex == 0{
//            return
//        }
//        var arequested = SoapRequestHelper()
//        arequested.requestStart("cancelOrder", parameters: [("orderId",self.currentOrderId),("md5","1111")],compeleteHandle: {(data, response, error) -> Void in
//            if error==nil{
//                self.hiddenProcessView()
//                let xmlHelper = XMLParseHelper(data: data,matchElement:"cancelOrderReturn",compeleteHandle:{responObj in
//                    if let dic = responObj as? NSDictionary{
//                        if (dic["result"] as! String) == "0"{
//                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                                self?.showTips("操作成功")
//                                self?.testSoap()
//                            })
//                        }
//                        else{
//                            dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                                self?.showTips("取消失败")
//                                })
//                        }
//                    }
//                })
//            }
//            else{
//                dispatch_async(dispatch_get_main_queue(), {[weak self] in
//                    self?.showTips("网络异常操作失败")
//                    })
//            }
//
//        })
//        self.showProcess("正在处理")
//    }
}